package org.duang.push;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//心跳超时处理类
public class HeartBeatDealHandler extends IdleStateAwareChannelHandler {
	private static Logger logger = LoggerFactory.getLogger(HeartBeatDealHandler.class);
	private long dayTimeMillis = 1000 * 60 * 60; // 一小时

	@Override
	public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
		if (System.currentTimeMillis() - e.getLastActivityTimeMillis() > dayTimeMillis) {
			try {
				Channel channel = e.getChannel();
				WebSocket.CHANNEL_MAP.remove(channel);
				channel.close();
				logger.debug("remove and close[ " + channel.getId() + " ] success!");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		// System.out.println(e.getChannel() + " event state:" + e.getState());
	}

//	int i=0;
//	@Override
//	public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
//		super.channelIdle(ctx, e);
//
//		if (e.getState() == IdleState.WRITER_IDLE)
//			i++;
//
//		if (i == 3) {
//			e.getChannel().close();
//			System.out.println("掉了。");
//		}
//	}
	
}
